package server

import (
	"context"
	"github.com/google/uuid"
	"github.com/spf13/viper"
	"strings"
	"uploadServer/protos"
)

// UploadServer 实现gRPC服务接口
type UploadServer struct {
	uploadpb.UnimplementedUploadServiceServer
}

// NewUploadServer 创建一个新的UploadServer实例
func NewUploadServer() *UploadServer {
	return &UploadServer{}
}

// GetUploadURL 实现gRPC服务的GetUploadURL方法
func (s *UploadServer) GetUploadURL(ctx context.Context, req *uploadpb.GetUploadURLRequest) (*uploadpb.UploadURLResponse, error) {
	endpoint := viper.GetString("minio.endpoint")
	accessKey := viper.GetString("minio.accessKey")
	secretKey := viper.GetString("minio.secretKey")
	bucket := viper.GetString("minio.bucket")

	// 获取文件后缀名
	ext := req.FileExtension
	if ext != "" && !strings.HasPrefix(ext, ".") {
		ext = "." + ext
	}

	// 生成唯一的objectName
	objectName := strings.ReplaceAll(uuid.New().String(), "-", "_") + ext

	client, err := NewMinioClient(endpoint, accessKey, secretKey, false)
	if err != nil {
		return nil, err
	}

	// 生成预签名上传URL（60秒后过期）
	putUrl, err := GetPresignedPutURL(client, bucket, objectName, 60)
	if err != nil {
		return nil, err
	}

	// 拼接公网访问路径
	publicHost := "http://" + endpoint
	publicUrl := ""
	if publicHost != "" {
		publicUrl = publicHost + "/" + bucket + "/" + objectName
	}

	return &uploadpb.UploadURLResponse{
		UploadUrl:  putUrl,
		ObjectName: objectName,
		FileUrl:    publicUrl,
	}, nil
}
